package com.beone.smart.smartBeauty.controller.webApi;

import com.beone.smart.smartBeauty.exception.GlobalException;
import com.beone.smart.smartBeauty.model.entity.GoodsDO;
import com.beone.smart.smartBeauty.model.form.GoodsCreateForm;
import com.beone.smart.smartBeauty.model.form.GoodsUpdateForm;
import com.beone.smart.smartBeauty.model.result.ResultEntity;
import com.beone.smart.smartBeauty.model.result.ResultTool;
import com.beone.smart.smartBeauty.service.intf.GoodsService;
import com.beone.smart.smartBeauty.utils.LocalTimeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;

/**
 * Created by bruce on 20/2/16 -- 15:37
 */
@Api(description = "商品管理")
@Slf4j
@RestController
@RequestMapping(value = "/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @ApiOperation(value = "获取商品列表", notes = "可分页")
    @GetMapping(value = "/list")
    public ResultEntity list() {
        return ResultTool.ok(goodsService.list());
    }

    @ApiOperation(value = "新增商品信息")
    @PostMapping(value = "/create")
    public ResultEntity create(@RequestBody GoodsCreateForm goodsCreateForm) {
        GoodsDO goodsDO = new GoodsDO();
        BeanUtils.copyProperties(goodsCreateForm, goodsDO);
        goodsDO.setCreateDate(LocalTimeUtil.getDateTime());
        return ResultTool.ok(goodsService.save(goodsDO));
    }

    @ApiOperation(value = "修改商品信息")
    @PostMapping(value = "/update")
    public ResultEntity update(@RequestBody GoodsUpdateForm goodsUpdateForm) {
        GoodsDO goodsDO = new GoodsDO();
        BeanUtils.copyProperties(goodsUpdateForm, goodsDO);
        return ResultTool.ok(goodsService.updateById(goodsDO));
    }

    @ApiOperation(value = "依据id获取商品详情")
    @ApiImplicitParam(name = "id", value = "商品id", required = true, dataType = "String")
    @GetMapping(value = "/getOne")
    public ResultEntity getOne(@RequestParam @NotBlank String id) {
        GoodsDO goodsDO = goodsService.getById(id);
        if (goodsDO == null) {
            throw new GlobalException(ResultTool.HttpResponseCode.NOT_FOUND, "查询为null，请检查id");
        }
        return ResultTool.ok(goodsDO);
    }

    @ApiOperation(value = "删除商品")
    @ApiImplicitParam(name = "id", value = "商品id", required = true, dataType = "String")
    @GetMapping(value = "/delete")
    public ResultEntity delete(@RequestParam @NotBlank String id) {
        GoodsDO goodsDO = goodsService.getById(id);
        if (goodsDO == null) {
            throw new GlobalException(ResultTool.HttpResponseCode.NOT_FOUND, "查询为null，请检查id");
        }
        return ResultTool.ok(goodsService.removeById(id));
    }
}
